<?php

namespace App\Repository;


use App\Models\Product;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

/**
 * Class ProductRepository
 * @package App\Repository
 */
class ProductRepository
{
    /**
     * @var Product
     */
    public $product;

    /**
     * ProductRepository constructor.
     * @param $product
     */
    public function __construct(Product $product)
    {
        $this->product = $product;
    }

    /**
     * 获取最新商品  默认15条
     * @param $count
     * @return $this
     */
    public function getMostRecent($count)
    {
        $products = $this->product->orderBy('created_at', 'desc')->limit($count)->get();

        if ($products->isEmpty()){
            throw new NotFoundHttpException('指定的商品不存在，请检查ID值', null, 30000);
        }
        return $products->makeHidden('summary');
    }

    /**
     * 获取分类下的商品
     * @param $id
     * @return \Illuminate\Database\Eloquent\Collection|static[]
     */
    public function getProductsByCategory($id)
    {
        $products = $this->product->where('category_id', $id)->get();
        if ($products->isEmpty()){
            throw  new NotFoundHttpException('改分类下没有相关的商品，请选择其他分类', null, 30000);
        }
        return $products;
    }


    /**
     *  获取商品详细信息
     * @param $id
     * @return \Illuminate\Database\Eloquent\Collection|\Illuminate\Database\Eloquent\Model|null|static|static[]
     */
    public function getProductDetail($id)
    {

//        return  $this->product->with(['images.imgUrl', 'properties'])->find($id);
        $product = $this->product
                ->with(['images' => function($query){
                    return $query->with(['imgUrl'])->orderBy('order', 'asc');
                }])
                ->with(['properties'])
                ->find($id);
        return $product;

    }

}